package com.hugo.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.hugo.oss.service.OssService;
import com.hugo.oss.utils.ConstandPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传文件到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstandPropertiesUtils.END_POINT;
        String accessKeyId = ConstandPropertiesUtils.KEYID;
        String accessKeySecret = ConstandPropertiesUtils.KEYSECRET;
        String bucketName = ConstandPropertiesUtils.BUCKETNAME;

        try{
            //创建OSS实例
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            //获取上传流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String Filename = file.getOriginalFilename();
            //在文件名里随机生成唯一的数
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            Filename = uuid+Filename;

            //创建日期文件统一管理 获取当前日期
            String datetime = new DateTime().toString("yyyy/MM/dd");
            Filename=datetime+"/"+Filename;


            //第一个名称bucketname  第二参数上传到oss的文件和文件路径 第三个 上传文件输入流
            ossClient.putObject(bucketName, Filename, inputStream);
            //关闭数据流
            ossClient.shutdown();

            //拼接地址 并且返回地址
            String url="https://"+bucketName+"."+endPoint+"/"+Filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;

        }


    }
}
